﻿using CoreModule;
using Microsoft.Extensions.Logging;
using Prism.Ioc;
using Prism.Modularity;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Yuwell.AtomizerWeight.App.Views;
namespace Yuwell.AtomizerWeight.App
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {


        /// <summary>
        /// 
        /// </summary>

        public App()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
            //当某个异常未被捕获时出现
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            //未被观察到的Task多线程异常
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

         
        }





        /// <summary>
        /// 
        /// </summary>
        string Args { get; set; }
        protected override void OnStartup(StartupEventArgs e)
        {

            ///先生成一个
            var dbConf = CoreModule.Storages.DbStorageConfiguration.Load();

            dbConf.Save();

            CoreModule.Storages.MySqlDbStorage.UpdateConnectionString(dbConf.IpAddress, dbConf.UserName, dbConf.UserPassword, dbConf.Database);

            CoreModule.Storages.MySqlDbStorage storage = new CoreModule.Storages.MySqlDbStorage();
            try
            {
                storage.Database.EnsureCreated();

            }
            catch (Exception ex)
            {


            }

            Args = string.Join(",", e.Args);
            base.OnStartup(e);

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            Logger.LogError(e.Exception.Message);
#if DEBUG
            MessageBox.Show("Current_DispatcherUnhandledException:" + (e.Exception.Message));
#endif
            Application.Current.Shutdown();
        }
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Logger.LogError((e.ExceptionObject as Exception).Message);
#if DEBUG
            MessageBox.Show("CurrentDomain_UnhandledException:" + (e.ExceptionObject as Exception).Message);
#endif
            Application.Current.Shutdown();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
        {
            Logger.LogError(e.Exception.Message);
#if DEBUG
            MessageBox.Show("TaskScheduler_UnobservedTaskException:" + (e.Exception.Message));
#endif
            Application.Current.Shutdown();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }
        [NotNull]
        IContainerRegistry ContainerRegistry { get; set; }
        [NotNull]
        Microsoft.Extensions.Logging.ILogger Logger { get; set; }

        /// <summary>
        /// 注册 类型
        /// </summary>
        /// <param name="containerRegistry"></param>
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {

            ContainerRegistry = containerRegistry;

            var factory = new NLog.Extensions.Logging.NLogLoggerFactory();
            Logger = factory.CreateLogger("NLog");

            containerRegistry.RegisterInstance(Logger);

            base.RegisterRequiredTypes(containerRegistry);
            containerRegistry.RegisterSingleton<IModuleInitializer, AppModuleInitializer>();

            containerRegistry.RegisterInstance<IContainerRegistry>(containerRegistry);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dateTime"></param>
        private void ClearLog(DateTime expireDateTime)
        {
            var logPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "logs");
            var files = System.IO.Directory.GetFiles(logPath, "*.log");
            foreach (var file in files)
            {
                var fileInfo = new System.IO.FileInfo(file);
                if (fileInfo.CreationTime < expireDateTime)
                {
                    try
                    {
                        System.IO.File.Delete(file);
                    }
                    catch (Exception e)
                    {
                        Logger.LogInformation(e.Message);
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnExit(ExitEventArgs e)
        {
            //var deviceManager = Container.Resolve<IDeviceManager>();
            //deviceManager.StopDevice();

            try
            {
                ClearLog(DateTime.Now.AddDays(-10));

                NLog.LogManager.Shutdown();

            }
            catch (Exception)
            {

            }

            base.OnExit(e);
        }
        /// <summary>
        /// 
        /// </summary>


        protected override void InitializeShell(Window shell)
        {


            var notifier = shell as INotifier;

            ContainerRegistry.RegisterInstance(notifier);

            var windowLifetime = shell.DataContext as IWindowLifetime;

            ContainerRegistry.RegisterInstance(windowLifetime);

            ContainerRegistry.RegisterInstance(shell.Dispatcher);

            base.InitializeShell(shell);
        }

        /// <summary>
        /// 
        /// </summary>
        protected override void OnInitialized()
        {

            base.OnInitialized();



        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected override IModuleCatalog CreateModuleCatalog()
        {

            var modulePath = "Modules";
            if (System.IO.Directory.Exists("Modules"))
            {
                return new AppDirectoryModuleCatalog() { ModulePath = modulePath };
            }
            else
            {
                return base.CreateModuleCatalog();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="moduleCatalog"></param>
        /// <param name="resLanguage"></param>
        private void ConfigureResourceLocalizationModule(IModuleCatalog moduleCatalog)
        {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="moduleCatalog"></param>
        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {

            ///核心模块
            if (!moduleCatalog.Modules.Any(item => item.ModuleName == "CoreModule"))
            {
                moduleCatalog.AddModule<CoreModule.Module>("CoreModule");
            }

            ConfigureResourceLocalizationModule(moduleCatalog);

            base.ConfigureModuleCatalog(moduleCatalog);
        }

    }
}
